const express = require('express')
const router = express.Router()
const jwt = require('../../jwt');

const { marked, Renderer } = require('marked')
const fs = require('fs')
const path = require('path')

const Article = require('../../models/article')

// 创建自定义的 Renderer 实例
const renderer = new Renderer();
// 重写 heading 方法，使其生成带有 class 的标题元素
// leave是h?,这里把所有的标题元素都变成h?
renderer.heading = function (text, level) {
  const className = 'heading-' + '2';
  return `<h${level} class="${className}"><span>${text}</span></h${level}>`;
};

//添加文章
//@POST /api/article/add
router.post('/add', (req, res) => {
  //根据token解析出来role，进行权限管理
  const { tokenKey } = jwt.verifyToken(req.headers.authorization)
  console.log(tokenKey)
  const role = tokenKey.rule.role
  if (role !== 'admin') {
    return res.send({
      state: 0,
      message: '没有操作权限'
    })
  }
  //添加前把md格式转换成html
  req.body.body_html = marked(req.body.body_md, { renderer })

  Article.create(req.body)
    .then(doc => {
      res.send({
        state: 1,
        message: '创建成功',
        doc: doc
      })
    })
    .catch(err => res.status(400).json(err.message))
})
//修改文章
//@POST /api/article/update
router.post('/update/:id', (req, res) => {

  //根据token解析出来role，进行权限管理
  const { tokenKey } = jwt.verifyToken(req.headers.authorization)
  console.log(tokenKey)
  const role = tokenKey.rule.role
  if (role !== 'admin') {
    return res.send({
      state: 0,
      message: '没有操作权限'
    })
  }
  //重新转换为html代码
  req.body.body_html = marked(req.body.body_md, { renderer })

  Article.findByIdAndUpdate(req.params.id, {
    title: req.body.title,
    body_md: req.body.body_md,
    body_html: req.body.body_html,
    class_name: req.body.class_name,
    tags: req.body.tags,
    create_user: req.body.create_user
  })
    .then(doc => {
      res.send({
        state: 1,
        message: '修改成功',
        doc: doc
      })
    })
    .catch(err => res.send({ data: err, state: 0, msg: '修改失败' }))
})
//查询所有文章
//@get /api/article/all
router.get('/all', (req, res) => {
  Article.find({})
    .then(doc => {
      res.send({
        state: 1,
        message: '查询成功',
        doc: doc
      })
    })
    .catch(err => res.status(400).json(err.message))
})
//分页查询文章
//@get /api/article/current
router.get('/current/:current/:pageSize', (req, res) => {
  Article.find({})
    .then(doc => {
      let artNum = doc.length //文章总数
      let current = req.params.current
      let pageSize = req.params.pageSize
      //根据传过来的页码和每页的文章数筛选出来数据
      let arr = doc.filter((item, index) => {
        return index >= (current - 1) * pageSize && index < current * pageSize
      })
      res.send({
        doc: arr,
        state: 1,
        msg: '分页查询成功',
        articleNum: artNum
      })
    })
    .catch(err => res.status(400).json(err.message))
})

//删除文章
//@DELETE /api/article/delete
router.delete('/delete/:id', (req, res) => {

  //根据token解析出来role，进行权限管理
  const { tokenKey } = jwt.verifyToken(req.headers.authorization)
  console.log(tokenKey)
  const role = tokenKey.rule.role
  if (role !== 'admin') {
    return res.send({
      state: 0,
      message: '没有操作权限'
    })
  }
  Article.findByIdAndDelete(req.params.id)
    .then(doc => {
      res.send({
        state: 1,
        message: '删除成功',
        doc: doc
      })
    })
    .catch(err => res.status(400).json(err.message))
})



//后续根据分类查找和其他功能待开发


module.exports = router